import React, { memo, useEffect, useState, useRef } from 'react'
import './style.less'
import { Space, Tree, Button, Modal, Flex } from 'antd'
import type { TreeProps } from 'antd/es/tree'
import { HsAdminInput } from '@hs-admin/base-components'

import { getPrefixList, deleteFileByIds } from '@/api/operationCenter/docMaintain'
import DocMaintainList from './List'
import Fileupload from '@/components/flie/Fileupload'
import ResolveFileList from '@/components/flie/ResolveFileList'
import { message } from '@hs-admin/utils'

const DocMaintain: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [treeData, settreeData]: any = useState([])
  const [fileId, setfileId]: any = useState([])
  const [treeid, settreeid]: any = useState(null)
  const [searchValue, setsearchValue]: any = useState('')
  const [searchNewValue, setsearchNewValue]: any = useState('')
  const ListRef = useRef<any>(null)
  const onSelect: TreeProps['onSelect'] = (selectedKeys) => {
    settreeid(selectedKeys[0])
  }
  function PrefixList() {
    getPrefixList({}).then((res: any) => {
      if (res) {
        const tree = filterFileList(res)
        settreeData(tree)
        if (treeid) return
        settreeid(res[0].id)
      }
    })
  }

  const getFile = () => {
    setsearchNewValue(searchValue)
  }

  /**
   * 递归处理 tree 数据
   * @param list tree 源数据
   */
  const filterFileList = (list: any, leval?: any) => {
    if (leval) {
      leval++
    } else {
      leval = 1
    }

    const array: any = []

    list.forEach((element: any) => {
      element.leval = leval

      element.title = element.label

      element.key = element.id

      if (element.children && element.children.length) element.children = filterFileList(element.children, leval)

      array.push(element)
    })

    return array
  }

  //上传确定
  function handleOk() {
    setIsModalOpen(false)
    ListRef.current.initPage()
    setfileId([])
  }

  const handleUploadSuccess = (file: any) => setfileId((arr: any) => [...arr, file.file.id])

  // 表单modal-文件删除
  const Filedelect = (e: any) => {
    setfileId(fileId.filter((id: any) => id !== e.value))
    deleteFileById(e.value)
  }

  //删除对应目录的文档
  function deleteFileById(id: any) {
    deleteFileByIds({ ids: [id] }).then((res: any) => {
      if (res) {
        message.success('操作成功')
        if (!isModalOpen) {
          ListRef.current.getFileByIds()
        }
      }
    })
  }

  useEffect(() => PrefixList(), [])

  function rednerIcon(nodeData: any): React.ReactNode {
    return (
      <Flex align="center" justify="space-between" className="h-50px">
        <span className="mr-20px">{nodeData.title}</span>
      </Flex>
    )
  }
  return (
    <div className="docMaintain-page-wrapper">
      <div className="docMaintain__left w-230px">
        <div className="docmet">文档目录</div>

        <Tree className="pb-10px" showIcon onSelect={onSelect} treeData={treeData} titleRender={(nodeData) => rednerIcon(nodeData)} />
      </div>
      <div className="docMaintain__right">
        <Space className="top">
          <HsAdminInput
            placeholder="请输入"
            defaultValue={searchValue}
            onChange={(e: any) => setsearchValue(e.target.value)}
            onPressEnter={getFile}
          />
          <Button onClick={getFile} type="primary">
            搜索
          </Button>
        </Space>
        <div className="mid"></div>
        <DocMaintainList ref={ListRef} id={treeid} searchValue={searchNewValue}></DocMaintainList>
      </div>
      <Modal centered title={'文档上传'} open={isModalOpen} closeIcon={null} footer={null}>
        <Fileupload
          success={(e) => handleUploadSuccess(e)}
          params={{ file_prefix_id: treeid, creator: '' }}
          name="file"
          accept=".rar,.zip,.doc,.docx,.xlsx,.pdf"></Fileupload>
        <div className="pt-15px">
          <ResolveFileList ids={fileId} edit={true} delect={Filedelect}></ResolveFileList>
        </div>
        <Flex justify="end">
          <Button onClick={handleOk} type="primary">
            确定
          </Button>
        </Flex>
      </Modal>
    </div>
  )
}

export default memo(DocMaintain)
